package gf.client.controller;


import gf.client.utils.HttpUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.time.LocalDate;

/**
 * 上传文件
 * @author Gaofeng
 * @since 2021/10/17 12:45
 **/

public class UploadController {
    public static String uploadFile(String uploadFilePaths) throws Exception {

        HttpURLConnection connection = HttpUtils.creatUtil("http://127.0.0.1:8080/file/upload", "POST");

        String fileType = uploadFilePaths.substring(uploadFilePaths.indexOf("."));
        File file = new File(uploadFilePaths);
        if (!file.exists()) {
            return "文件路径不存在";
        }
        connection.setRequestProperty("fileSize", String.valueOf(file.length()));
        connection.setRequestProperty("fileType", fileType);
        connection.setRequestProperty("fileName", URLEncoder.encode(file.getName(), "UTF-8"));

        /*
         * 获取日期
         */
        LocalDate today = LocalDate.now();

        connection.setRequestProperty("time", today.toString());

        OutputStream out = new DataOutputStream(connection.getOutputStream());

        /*
         *  取得文件的FileInputStream
         */
        FileInputStream fStream = new FileInputStream(uploadFilePaths);

        int bufferSize = 2048;
        byte[] buffer = new byte[bufferSize];
        int length ;

        /*
         * 读取时文件数据至缓冲区
         */
        while ((length = fStream.read(buffer)) != -1) {
        //写入文件
            out.write(buffer, 0, length);
        }
        fStream.close();
        out.flush();
        //读取文件内容
        InputStream inputStream = connection.getInputStream();
        int ch;
        StringBuilder sb = new StringBuilder();
        while ((ch = inputStream.read()) != -1) {
            sb.append((char) ch);
        }

        System.out.println("上传成功" + sb.toString().trim());
        out.close();
        return "上传成功";
    }
}
